<template>
  <div>
    <div style="margin-bottom: 5px">
      <el-input v-model="name" placeholder="请输入用户名" suffix-icon="el-icon-search" style="width: 200px"
                @keyup.enter.native="search"></el-input>
      <el-button type="primary" style="margin-left: 5px" @click="search">查询</el-button>
      <el-button type="success" @click="resetParam">重置</el-button>
      <el-button type="primary" style="margin-left: 5px" @click="add">新增</el-button>
    </div>
    <el-table :data="tableData"
              :header-cell-style="{background:'#f2f5fc',color:'#555'}"
              border>
      <el-table-column prop="id" label="ID" width="60">
      </el-table-column>
      <el-table-column prop="userName" label="用户名" width="120">
      </el-table-column>
      <el-table-column prop="phone" label="联系方式" width="160">
      </el-table-column>
      <el-table-column prop="role" label="角色" width="80">
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="200">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="上次修改时间" width="200">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="operate" label="操作">
        <template slot-scope="scope">
          <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
          <el-popconfirm title="确定删除吗？" @confirm="del(scope.row.userName)" style="margin-left: 5px">
            <el-button slot="reference" size="small" type="danger">删除</el-button>
          </el-popconfirm>
          <el-button size="small" type="primary" @click="send(scope.row)" style="margin-left: 5px">发消息</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        :current-page="pageNum"
        :page-sizes="[5, 10, 20,30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    >
      <!--        @size-change="handleSizeChange"-->
      <!--        @current-change="handleCurrentChange"-->
    </el-pagination>

    <el-dialog
        title="提示"
        :visible.sync="centerDialogVisible"
        @close="flag=0"
        width="30%"
        center>

      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="用户名" prop="userName">
          <el-col :span="20">
            <el-input v-if="flag==0" v-model="form.userName" disabled></el-input>
            <el-input v-else v-model="form.userName"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="this.flag==1">
          <el-col :span="20">
            <el-input v-model="form.password"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-col :span="20">
            <el-select v-model="form.role">
              <el-option v-if="form.role != 'admin'" label="admin" value="admin"></el-option>
              <el-option v-if="form.role != 'hospital'" label="hospital" value="hospital"></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-col :span="20">
            <el-input v-model="form.phone"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
        title="发送信息"
        :visible.sync="centerSend"
        @close="flag=0"
        width="30%"
        center>

      <el-form ref="message" :model="message" label-width="80px">
        <el-form-item label="发送者" prop="password">
          <el-col :span="20">
            <el-input v-model="message.senderName" disabled></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="接收者Id" prop="receiver">
          <el-col :span="20">
            <el-input v-model="message.receiver" disabled></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="title" prop="title">
          <el-col :span="20">
            <el-input v-model="message.title"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-col :span="20">
            <el-input type="textarea" v-model="message.content"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerSend = false">取 消</el-button>
        <el-button type="primary" @click="sendSucc">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {deleteUserByUsername, mohuselectAll, selectAllUser, updateUserByUsername, userRegister} from "@/api/user";
import {addMessage} from "@/api/messaage";

export default {
  name: "UserManage",
  data() {
    return {
      flag: 0,
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      name: '',
      sex: '',
      sexs: [
        {
          value: '1',
          label: '男'
        }, {
          value: '0',
          label: '女'
        }
      ],
      centerDialogVisible: false,
      centerSend: false,
      form: {
        id: "",
        password: "",
        phone: "",
        role: "",
        userName: "",
      },
      message: {
        content: "",
        receiver: "",
        senderName: "",
        title: "",
        receiverName:""
      }
    }
  },
  methods: {
    restForm() {
      this.$refs.form.resetFields();
    },
    search() {
      if (this.name != null && this.name !== '') {
        console.log(this.name)
        mohuselectAll({
          name: this.name
        }).then((res) => {
          if (res.flag == true) {
            this.tableData = res.data
            this.total = res.data.length
            console.log(this.tableData + "  " + this.total)
          } else {
            alert("获取数据失败")
          }
        })
      } else {
        this.loadPost()
      }
    },
    mod(row) {
      console.log(row)

      this.centerDialogVisible = true
      this.$nextTick(() => {
        //要赋值到表单
        this.form.userName = row.userName
        this.form.phone = row.phone
        this.form.role = row.role
      })
    },
    del(userName) {
      console.log(userName)
      deleteUserByUsername({
        userName: userName
      }).then((res) => {
        if (res.flag == true) {
          this.$message.success("用户删除成功")
          this.loadPost()
        } else {
          this.$message.error(res.data);
        }
      })
          .catch((err) => {
            console.log("删除失败");
          });
    },
    send(row) {
      console.log(row)
      this.centerSend = true
      this.$nextTick(() => {
        //要赋值到表单
        this.message.senderName = this.$store.state.userName
        this.message.receiver = row.id
        this.message.receiverName=row.userName
      })
    },
    add() {
      this.flag = 1
      this.centerDialogVisible = true
      this.$nextTick(() => {
        this.restForm()
      })
    },
    doSave() {
      if (this.form.userName === "" || this.form.userName == null) {
        alert("用户名不能为空");
        return;
      }
      if (this.form.password == "" || this.form.password == null) {
        alert("密码不能为空");
        return;
      }
      if (this.form.role == "" || this.form.role == null) {
        alert("角色不能为空");
        return;
      }
      if (this.form.phone == "" || this.form.phone == null) {
        alert("手机号码不能为空");
        return;
      }
      userRegister({
        userName: this.form.userName,
        password: this.form.password,
        role: this.form.role,
        phone: this.form.phone,
      }).then((res) => {
        if (res.flag == true) {
          this.$message.success("新增用户成功");
          this.centerDialogVisible = false
          this.loadPost()
          this.flag = 0
        } else {
          this.$message.error(res.data);
        }
      })
          .catch((err) => {
            console.log("新增失败");
          });
    },
    doMod() {
      updateUserByUsername({
        userName: this.form.userName,
        phone: this.form.phone,
        role: this.form.role
      })
          .then((res) => {
            if (res.flag == true) {
              this.$message.success("修改成功");
              this.centerDialogVisible = false
              this.loadPost()
            } else {
              this.$message.error(res.data);
            }
          })
          .catch((err) => {
            console.log("修改失败");
          });
    },
    doSend() {
      addMessage({
        content: this.message.content,
        receiver: this.message.receiver,
        senderName: this.message.senderName,
        title: this.message.title
      }).then((res) => {
        if (res.flag == true) {
          this.$message.success("发送给【"+this.message.receiverName+"】成功");
          this.centerSend = false
          this.loadPost()
        } else {
          this.$message.error(res.data);
        }
      }).catch((err) => {
        console.log("修改失败");
      });
    },
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.flag == 0) {
            this.doMod()
            console.log("修改")
          } else if (this.flag == 1) {
            this.doSave()
            console.log("增加")
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    sendSucc() {
      this.doSend()
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum = 1;
      this.pageSize = val;
      this.loadPost()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val;
      this.loadPost()
    },
    resetParam() {
      this.name = ''
      this.sex = ''
    },
    loadPost() {
      this.flag = 0
      selectAllUser({}).then((res) => {
        if (res.flag == true) {
          this.tableData = res.data
          console.log(this.tableData)
          this.total = res.data.length
        } else {
          alert("获取数据失败")
        }
      })
    },
    formatDateTime(dateTimeString) {
      const backendDate = new Date(dateTimeString);
      const year = backendDate.getFullYear();
      const month = String(backendDate.getMonth() + 1).padStart(2, '0');
      const day = String(backendDate.getDate()).padStart(2, '0');
      const hours = String(backendDate.getHours()).padStart(2, '0');
      const minutes = String(backendDate.getMinutes()).padStart(2, '0');
      const seconds = String(backendDate.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
  },
  beforeMount() {
    this.loadPost()
  }
}
</script>

<style scoped>

</style>